package com.example.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * http请求上下文工具类
 * @author hutu
 * @date 2018/3/28 11:20
 */
public class HttpContextUtils {
	private static final Logger logger = LoggerFactory.getLogger(HttpContextUtils.class);
	private static final String TOKEN = "token";
	private static final String EXPIRE = "expire";
	public static HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}
	/**
	 * 获取请求的token
	 */
	public static String getRequestToken(){
		return getRequestParameter(TOKEN);
	}
	/**
	 * 获取请求的expire
	 */
	public static String getRequestExpire(){
		return getRequestParameter(EXPIRE);
	}
	/**
	 * 从请求头或体里获取请求中指定参数
	 */
	public static String getRequestParameter(String param){
		HttpServletRequest httpServletRequest = getHttpServletRequest();
		//从header中获取
		String value = httpServletRequest.getHeader(param);
		//如果header中不存在
		if (StringUtils.isBlank(value)) {
			value = httpServletRequest.getParameter(param);
			if (StringUtils.isBlank(value)) {
				logger.error("从Request获取参数:"+param+" 失败");
				value = null;
			}
		}
		return value;
	}

	public static HttpSession getHttpSession(){
		return getHttpServletRequest().getSession();
	}
	public static String getSessionParameter(String param){
		return (String)getHttpSession().getAttribute(param);
	}
	public static void setSessionParameter(String key,String value){
		getHttpSession().setAttribute(key,value);
	}
}
